﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightApplication4.ServiceReference1;
using SilverlightApplication4.Util;

namespace SilverlightApplication4
{
    public partial class MainPage : UserControl, IERPModule
    {
        AppUtil util;
        public List<BusinessObject> lstObjects = new List<BusinessObject>();
        Object _mainObject;

        DALClient dal;

        String strPhieuNhap = "PHIEU_NHAP";
        String strChiTietPhieuNhap = "CHI_TIET_PHIEU_NHAP";

        int iCurrentItemIndex = -1;

        ItemWindow itemWindow;
        public Object MainObject
        {
            set
            {
                _mainObject = value;
            }
            get 
            {
                return _mainObject;
            }

        }

        public List<Control> lstElements
        {
            set;
            get;
        }

        public List<Control> lstIndexControls
        {
            set;
            get;
        }

        public List<CHI_TIET_PHIEU_NHAP_Extend> lstReceiptItems = new List<CHI_TIET_PHIEU_NHAP_Extend>();

        public MainPage()
        {
            util = new AppUtil(this);
            InitializeComponent();
            LayoutUpdated += MainPage_LayoutUpdated;
            Loaded += MainPage_Loaded;
            lstElements = new List<Control>();
            lstIndexControls = new List<Control>();
            dal = new DALClient();

            InitData();
            InitUI();
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //System.Windows.Browser.HtmlPage.Plugin.Focus();
            //NoTextBox.Focus();
            Dispatcher.BeginInvoke(() => { NoTextBox.Focus(); });
        }

        public void SetFocus(Control control)
        {
            Dispatcher.BeginInvoke(() => { control.Focus(); });
        }

        void MainPage_LayoutUpdated(object sender, EventArgs e)
        {
            
        }

        public Object GetObject(string strTable)
        {
            foreach (BusinessObject obj in lstObjects)
            {
                if (obj.TableName == strTable)
                    return obj.Obj;
            }

            return null;
        }

        public void AddObject(string strTable, Object obj)
        {
            lstObjects.Add(new BusinessObject(strTable, obj)) ;
        }

         
        public void AssignObject(string strTable, Object obj)
        {
            for (int i = 0; i < lstObjects.Count; i++)
            {
                if (lstObjects[i].TableName == strTable)
                {
                    lstObjects[i].Obj = obj;
                    break;
                }
            }

            ValidateItemList(strTable);
        }

        public void InitData()
        {
            PHIEU_NHAP rcp = new PHIEU_NHAP();
            AddObject(strPhieuNhap, rcp);
            AssignObject(strPhieuNhap, rcp);

            ValidateItemList(strPhieuNhap);

            CHI_TIET_PHIEU_NHAP_Extend chitiet = new CHI_TIET_PHIEU_NHAP_Extend();
            AddObject(strChiTietPhieuNhap, chitiet);
            AssignObject(strChiTietPhieuNhap, chitiet);

        }

        public void InitUI()
        {
            //LayoutRoot.KeyDown += LayoutRoot_KeyDown;
            NoTextBox.KeyDown += NoTextBox_KeyDown;

            util.InitControls(LayoutRoot, InitType.All);

            ItemGrid.MouseLeftButtonUp += ItemGrid_MouseLeftButtonUp;
            ItemGrid.KeyDown += ItemGrid_KeyDown;

            itemWindow = new ItemWindow();
            itemWindow.Closed += itemWindow_Closed;
            util.InitControls(itemWindow.LayoutRoot, InitType.All);


            lstIndexControls.Sort(new Comparison<Control>((e1, e2) => { return e1.TabIndex.CompareTo(e2.TabIndex); }));
           // lstElements.Sort(new 

        }

        void ItemGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ///get the data object of the row
            if (ItemGrid.SelectedItem != null)
            {
                iCurrentItemIndex = ItemGrid.SelectedIndex;
                AssignObject(strChiTietPhieuNhap, ItemGrid.SelectedItem);
                itemWindow.Init(EditItemType.Edit);
            }
            else
            {
                iCurrentItemIndex = -1;
                AssignObject(strChiTietPhieuNhap, new CHI_TIET_PHIEU_NHAP_Extend());
                itemWindow.Init(EditItemType.New);
            }

            util.InitControls(itemWindow.LayoutRoot, InitType.Binding);
            itemWindow.Show();
            
        }

        void itemWindow_Closed(object sender, EventArgs e)
        {
            ItemWindow window = (ItemWindow)sender;

            if (window.DialogResult == true)
            {
                if (window.type == EditItemType.New)
                {
                    lstReceiptItems.Add((CHI_TIET_PHIEU_NHAP_Extend)GetObject(strChiTietPhieuNhap));
                }
                else if (window.type == EditItemType.Edit)
                {
                    if (iCurrentItemIndex >= 0)
                        lstReceiptItems[iCurrentItemIndex] = (CHI_TIET_PHIEU_NHAP_Extend)GetObject(strChiTietPhieuNhap);
                    
                }
                RefreshItemGrid();
            }
        }

        void ItemGrid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {

            }
        }

        void ItemGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        void NoTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            String strSearch = NoTextBox.Text;

            DALClient client = new DALClient();

            if (e.Key == Key.Enter)
            {
                if (String.IsNullOrEmpty(strSearch) == false)
                {
                    client.GetReceiptAsync(strSearch);
                    client.GetReceiptCompleted += client_GetReceiptCompleted;
                }
            }

            if (e.Key == Key.F12)
            {
                util.InitSearchPopup(NoTextBox, "PHIEU_NHAP", SetMainObjectByID);
            }
        }

        public void SetMainObjectByID(object sender, EventArgs e)
        {
            String strPhieuPhapID = NoTextBox.Text;

            DALClient client = new DALClient();
            client.GetReceiptAsync(strPhieuPhapID);
            client.GetReceiptCompleted +=client_GetReceiptCompleted;
        }

        void client_GetReceiptCompleted(object sender, GetReceiptCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                AssignObject(strPhieuNhap, e.Result);
            }
            else
            {
                AssignObject(strPhieuNhap, new PHIEU_NHAP());
            }

            ValidateItemList(strPhieuNhap);
            util.InitControls(LayoutRoot, InitType.Binding);
        }

        

        void client_GetObjectsCompleted(object sender, GetObjectsCompletedEventArgs e)
        {
        }

        void client_QueryCompleted(object sender, QueryCompletedEventArgs e)
        {
            
        }

       

        void window_Closed(object sender, EventArgs e)
        {
            SearchWindow window = (SearchWindow)sender;

            if (window.SelectedObject != null)
            {
                MainObject = window.SelectedObject;
                AssignObject("PHIEU_NHAP", window.SelectedObject);
            }

            util.InitControls(LayoutRoot, InitType.Binding);
        }

        public void ValidateItemList(String strTable)
        {
            Object mainObj =  GetObject(strTable);
            if (mainObj != null && mainObj is PHIEU_NHAP && String.IsNullOrEmpty(((PHIEU_NHAP)mainObj).ID) == false)
            {
                DALClient client = new DALClient();
                client.GetReceiptItemsAsync(((PHIEU_NHAP)mainObj).ID);
                client.GetReceiptItemsCompleted += client_GetReceiptItemsCompleted;
            }
        }

        void client_GetReceiptItemsCompleted(object sender, GetReceiptItemsCompletedEventArgs e)
        {
            try
            {
                lstReceiptItems = e.Result.ToList();
                RefreshItemGrid();
            }
            catch (Exception ex)
            {
            }
            
        }

        public void RefreshItemGrid()
        {
            ItemGrid.AutoGenerateColumns = false;
            ItemGrid.ItemsSource = lstReceiptItems;
        }

        public void SetTips(string tips)
        {
            LabelTip.Content = tips;
        }
    }
}

